<?php
class CMatchinfo extends Zend_Db_Table
{
	protected $_name;
	protected $_primary;
	
	public function __construct()
	{
		$this->_name = R_PRE."matchinfo";
		$this->_primary = "MatchID";
		parent::__construct();
	}

	/**
	 * 新增比赛
	 * @param array $param
	 * @throws Exception
	 */
	public function insertMatch($param = array())
	{
		$db=$this->getAdapter();
		if(empty($param) || !is_array($param))
    		throw new Exception('参数错误!');
    	try{
	    	$db->insert ($this->_name, array(
		    		'MatchTime'				=> $param['MatchTime'],
		    		'TeamA'					=> $param['TeamA'],
		    		'TeamAScore'			=> $param['TeamAScore'],
		    		'TeamB'					=> $param['TeamB'],
	    			'TeamBScore'			=> $param['TeamBScore'],
		    		'MatchStatus'			=> $param['MatchStatus'],
		    		'TeamALogo'				=> $param['TeamALogo'],
		    		'TeamBLogo'				=> $param['TeamBLogo'],
		    		'MatchLogo'				=> $param['MatchLogo'],
	    	));
	    	$matchid = $db->lastInsertId();
			$array_ext1 = array(
			 	'TeamID'				=> $param['TeamA'],
				'Rate'					=> $param['TeamARate'],
				'MatchID'				=> $matchid,
			);
			$array_ext2 = array(
			 	'TeamID'				=> $param['TeamB'],
				'Rate'					=> $param['TeamBRate'],
				'MatchID'				=> $matchid,
			);
	    	$db->insert ('zcshop_matchrate',$array_ext1);
	    	$db->insert ('zcshop_matchrate',$array_ext2);
    	}catch(Exception $e) {
    		throw new Exception($e->getMessage());
    	}
	}
	
	/**
	 * 删除比赛
	 * @param int $id
	 */
	public function deleteMatch($id)
	{
		$db=$this->getAdapter();
		$result=$db->query("DELETE FROM $this->_name WHERE MatchID = $id");
		if($result > 0) {
			$db->query("DELETE FROM zcshop_matchrate WHERE MatchID = $id");
		}
		return $result;
	}
	
	/**
	 * 更新比赛
	 * @param array $param
	 */
	public function updateMatchAdmin($param = array())
	{
		$db=$this->getAdapter();
		try{
	    	if(empty($param) || !is_array($param))
	    		throw new Exception('参数错误!');
	    	$db->update ($this->_name, array(
		    		'MatchTime'				=> $param['MatchTime'],
		    		'TeamA'					=> $param['TeamA'],
		    		'TeamAScore'			=> $param['TeamAScore'],
		    		'TeamB'					=> $param['TeamB'],
	    			'TeamBScore'			=> $param['TeamBScore'],
		    		'TeamALogo'				=> $param['TeamALogo'],
		    		'TeamBLogo'				=> $param['TeamBLogo'],
		    		'MatchLogo'				=> $param['MatchLogo'],
		    		'MatchStatus'			=> $param['MatchStatus']),$db->quoteInto ('MatchID=?', $param['MatchID']));
			$Aiswin = 0;
			$Biswin = 0;
			if($param['MatchStatus'] == 2 && ($param['TeamAScore'] > 0 || $param['TeamBScore'] > 0))
			{
				if($param['TeamAScore'] > $param['TeamBScore']) {
					$Aiswin = 1;
    			} else {
    				$Biswin = 1;
    			}
    		}
			$array_ext1 = array(
			 	'TeamID'				=> $param['TeamA'],
				'Rate'					=> $param['TeamARate'],
				'MatchID'				=> $param['MatchID'],
				'IsWin'					=> $Aiswin,
			);
			$array_ext2 = array(
			 	'TeamID'				=> $param['TeamB'],
				'Rate'					=> $param['TeamBRate'],
				'MatchID'				=> $param['MatchID'],
				'IsWin'					=> $Biswin,
			);
			$db->update ('zcshop_matchrate',$array_ext1,$db->quoteInto ('MatchRateID=?', $param['TeamARateID']));
			$db->update ('zcshop_matchrate',$array_ext2,$db->quoteInto ('MatchRateID=?', $param['TeamBRateID']));
    	}catch(Exception $e) {
    		throw new Exception($e->getMessage());
    	}
	}
	
	public function fetchAllMatch($page, $pageNum, $statu = -1)
	{
		$where = null;
		$order = 'MatchID ASC';
		
		if ($statu != -1) {
			$where['MatchStatus = ?'] = $statu;
		}
		
		if ($statu == -2) {
			unset($where['MatchStatus = ?']);
			$where['MatchStatus <> ?'] = '0';
		}
		
		$offset = ($page -1) * $pageNum;
		return $this->fetchAll($where, $order, $pageNum, $offset);
	}
	
	public function getPageCount($pageNum, $statu = -1)
	{
		$where = null;
		
		if ($statu != -1) {
			$where['MatchStatus = ?'] = $statu;
		}
		
		$result = $this->fetchAll($where);
		
		return ceil(count($result)/$pageNum);
	}
	
	public function getTeam($flid)
	{
		$db = $this->getAdapter();
		$select = $db->select();
		$select->from(R_PRE . 'productfls', '*')
			   ->where('flid = ?', $flid);
		return $db->fetchRow($select);
	}
	
	public function getRate($matchId, $teamId)
	{
		$db = $this->getAdapter();
		$select = $db->select();
		$select->from(R_PRE . 'matchrate', '*')
			   ->where('MatchID = ?', $matchId)
			   ->where('TeamID = ?', $teamId);
		return $db->fetchRow($select);
	}
	
	public function addChipin($row, $member, $team)
	{
		$db = $this->getAdapter();
		$db->beginTransaction();
		try {
			$chipin = new CChipin();
			$chipin->add($row);
			$member->updateUserDetail(array('integral'=>new Zend_Db_Expr('integral - ' . $row['ChipInScore'])), array('uid'=>$row['UID']));
			$this->updateMatch(array($team=>new Zend_Db_Expr($team . '+' . $row['ChipInScore'])), $row['MatchID']);
			$fenlei = new CFenlei('product');
			$fenlei->refreshIntegral();
			$db->commit();
			return true;
		} catch(Exception $e) {
			$db->rollback();
			return false;
		}
	}
	
	public function updateMatch($row, $matchId)
	{
		$db = $this->getAdapter();
		$where = $db->quoteInto('MatchID = ?', $matchId);
		return $this->update($row, $where);
	}
	
	/**
	 * 比赛列表,关联球队
	 * @param int $from
	 * @param int $counts
	 * @param array $fieldArray
	 */
	public function getAll($from,$counts,$fieldArray=null){
		$db=$this->getAdapter();
		$where = ' where 1=1';
		if(isset($fieldArray['MatchStatus']) && $fieldArray['MatchStatus'] != '')
		{
			$where .= ' and t1.MatchStatus='.$fieldArray['MatchStatus'];
		}
		$limit = " LIMIT $from, $counts";
		$sql = 'SELECT t1.*,t2.flname as TeamAN,t2.en_flname as TeamANCN,t3.flname as TeamBN,t3.en_flname as TeamBNCN FROM zcshop_matchinfo t1 left join zcshop_productfls t2 on t1.TeamA=t2.flid left join zcshop_productfls t3 on t1.TeamB=t3.flid' . $where . ' order by t1.MatchID desc' . $limit;
		return $db->fetchAll($sql);
	}
	
	/**
	 * 比赛列表总记录数
	 * @param array $fieldArray
	 */
	public function getCounts($fieldArray=null){
		$db=$this->getAdapter();
		$select=$db->select();
		$select->from($this->_name,'COUNT(*)');
		if($fieldArray!=null){
			foreach ($fieldArray as $field => $value){
				$where = $db->quoteInto("$field = ?", $value);
				$select->where($where);
			}
		}
		return $db->fetchOne($select);
	}
	
	/**
	 * 比赛详细
	 * @param int $id
	 */
	public function getDetail($id)
	{
		
	}
	
	/**
	 * 发放奖励
	 * @param int $id
	 */
	public function GrantPrize($id = null)
	{
		try{
			if($id == null)
				throw new Exception('参数错误!');
			$db=$this->getAdapter();
			$db->query("CREATE TEMPORARY TABLE tmp_integralgrantprize select t1.UID, sum(t1.ChipInScore*t2.Rate) as Score from `zcshop_chipin` t1,`zcshop_matchrate` t2 where t1.MatchID=$id and t1.MatchID=t2.MatchID and t1.RateID=t2.MatchRateID and t2.IsWin=1 group by t1.UID");
			$db->query("update `zcshop_members` s1 inner join `tmp_integralgrantprize` s2 on s1.`uid` = s2.`UID` set s1.`integral` = s1.`integral` + s2.`Score` where s1.`uid` = s2.`UID`");
			$db->query("update `zcshop_chipin` set Status=1 where MatchID=$id");
			
			//update `zcshop_chipin` set GetScore=`zcshop_chipin`.ChipInScore*`zcshop_matchrate`.Rate from `zcshop_chipin` ,`zcshop_matchrate` where `zcshop_chipin`.MatchID=$id and `zcshop_chipin`.MatchID=`zcshop_matchrate`.MatchID and `zcshop_chipin`.RateID=`zcshop_matchrate`.MatchRateID and `zcshop_matchrate`.IsWin=1
			$db->query("update `zcshop_chipin` as s1 inner join `zcshop_matchrate` as s2 on s1.MatchID = s2.MatchID set s1.GetScore=s1.ChipInScore*s2.Rate where s2.IsWin=1 and s1.MatchID=$id and s1.RateID=s2.MatchRateID");
			$returnscore = $db->fetchOne("SELECT SUM(GetScore) from `zcshop_chipin` ,`zcshop_matchrate` where `zcshop_chipin`.MatchID=$id and `zcshop_chipin`.MatchID=`zcshop_matchrate`.MatchID and `zcshop_chipin`.RateID=`zcshop_matchrate`.MatchRateID and `zcshop_matchrate`.IsWin=1");
			//$returnscore = $db->fetchOne("SELECT SUM(Score) FROM tmp_integralgrantprize");
			$returnscore = $returnscore ? $returnscore : 0;
			$db->query("update `zcshop_matchinfo` set MatchStatus=3,ReturnScore=$returnscore where MatchID=$id");
			//
			//刷新分类积分
			$fenlei = new CFenlei('product');
			$fenlei->refreshIntegral();
		}catch(Exception $e) {
    		throw new Exception($e->getMessage());
    	}
	}
	
	/**
	 * 比赛详细,编辑
	 * @param int $id
	 */
	public function GetMatch($mid = null)
	{
		$db=$this->getAdapter();
		if($mid == null)
			return;
		$data = $db->fetchRow('select * from '.$this->_name.' where MatchID='.$mid);
		if(!empty($data)) {
			$ext1 = $db->fetchRow('select * FROM zcshop_matchrate where MatchID='.$mid.' and TeamID='.$data['TeamA']);
			$ext2 = $db->fetchRow('select * FROM zcshop_matchrate where MatchID='.$mid.' and TeamID='.$data['TeamB']);
			$data['TeamARate'] = $ext1['Rate'];
			$data['TeamARateID'] = $ext1['MatchRateID'];
			$data['TeamBRate'] = $ext2['Rate'];
			$data['TeamBRateID'] = $ext2['MatchRateID'];
		} else {
			die('错误的参数!');
		}
		return $data;
	}
	
	/**
	 * 比赛详细
	 * @param int $mid
	 */
	public function GetMatchDetail($mid = null)
    {
    	$db=$this->getAdapter();
    	if($mid == null)
			return;
		$data = $db->fetchRow('SELECT t1.*,t1.ChipInB+t1.ChipInA as ChipInTotal,t2.flname as TeamAN,t2.en_flname as TeamANCN,t3.flname as TeamBN,t3.en_flname as TeamBNCN FROM zcshop_matchinfo t1 left join zcshop_productfls t2 on t1.TeamA=t2.flid left join zcshop_productfls t3 on t1.TeamB=t3.flid where t1.MatchID='.$mid);
		if(!empty($data)) {
			$ext1 = $db->fetchRow('select * FROM zcshop_matchrate where MatchID='.$mid.' and TeamID='.$data['TeamA']);
			$ext2 = $db->fetchRow('select * FROM zcshop_matchrate where MatchID='.$mid.' and TeamID='.$data['TeamB']);
			$data['TeamARate'] = $ext1['Rate'];
			$data['TeamBRate'] = $ext2['Rate'];
		} else {
			die('错误的参数!');
		}
		return $data;
    }
    
    /**
     * 未用到
     * @param unknown_type $mid
     * @param unknown_type $page
     * @param unknown_type $per_page
     * @param unknown_type $param
     */
	public function GetChipinByMatch($mid = null,$page, $per_page, $param)
    {
    	if($mid == null)
			return;
		$where = ' where t1.MatchID='.$mid.' ';
		$appendurl = '';
		
		$totalNum = $this->_db->fetchOne ('select count(*) from QPNBADB..ChipIn t1' . $where);
        $pageInfo = $this->multi($totalNum, $per_page, $page, '/nbamatch/matchdetail/mid/'.$param['mid'].'/'.$appendurl);
        
        ($page) ? $page : 1;
        $s = $per_page * ($page - 1);
        $e = $per_page * $page;
        
		$sql = "SELECT * FROM (SELECT row_number() over (ORDER BY t1.ChipInID DESC) row,t1.*,t2.TeamID,t2.BigOrSmall FROM QPNBADB..ChipIn t1 left join QPNBADB..MatchRate t2 on t2.MatchRateID=t1.RateID ".$where.") sfaf WHERE row>'".$s."' and row <='".$e."'";
		$list     = $this->_db->fetchAll ($sql);
        return Array ('page' => $pageInfo, 'list' => $list);
		
    }
    
    public function refreshStatus()
    {
    	$db=$this->getAdapter();
    	$db->query("update `zcshop_matchinfo` set MatchStatus=1 where UNIX_TIMESTAMP()>=MatchTime and MatchStatus=0");
    }
}